package com.zmn.oms.api.controller.order;

import com.alibaba.fastjson.JSON;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.bo.order.OrderBO;
import com.zmn.oms.model.dto.order.create.CallCenterOrderCluesDTO;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.zmn.business.interfaces.work.autoflow.WorkFlowContextBService;
import com.zmn.oms.zmn.facade.interfaces.order.CreateOrderFacade;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 类描述：
 *
 * @author lhl
 * @date 2020/01/31 21:44
 */
@RestController
@RequestMapping("/clues/order")
@Slf4j
public class CallCenterOrderController {

    private static final String TAG = "oms-order-callCenter";

    @Autowired
    private CreateOrderFacade createOrderFacade;
    @Autowired
    private WorkFlowContextBService workFlowContextBService;

    /**
     * 创建订单
     *
     * @param callCenterOrderCluesDTO 订单信息
     * @return
     */
    @PostMapping("/create")
    @ResponseBody
    @SuppressWarnings("all")
    public ResultDTO createOrder(@Valid @RequestBody CallCenterOrderCluesDTO callCenterOrderCluesDTO) {
        log.info("[{}-createOrder] {}", TAG, JSON.toJSONString(callCenterOrderCluesDTO));

        // 地址或产品信息不全时，remark字段不能为空，该字段中以文本形式描述了订单的基本信息
        if ((StringUtils.isBlank(callCenterOrderCluesDTO.getAddress()) || StringUtils.isBlank(callCenterOrderCluesDTO.getProduct()))
                && StringUtils.isBlank(callCenterOrderCluesDTO.getRemark())) {
            return ResultDTO.fail("操作失败：地址或产品信息不全时，remark字段不能为空");
        }

        try {
            ResultDTO<OrderBO> resultDTO = createOrderFacade.createOrderByCallCenterOrderClues(callCenterOrderCluesDTO);

            if (!resultDTO.isStatusBool()) {
                return ResultDTO.fail("操作失败：" + resultDTO.getMessage());
            }

            // 工单自动流转，自动流转出现异常，不影响下单结果
            OrderBO orderBO = resultDTO.getData();
            try {
                OrderWork orderWork = orderBO.getOrderWork();
                workFlowContextBService.asyncAutoFlow(orderWork.getOrderId(),orderWork.getWorkId());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }

            return ResultDTO.success(orderBO.getOrder());
        } catch (OmsBaseException obe) {
            log.error(obe.getMessage(), obe);
            return ResultDTO.fail("操作失败：" + obe.getMessage());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultDTO.fail("操作失败");
        }
    }
}
